package org.test.portlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ResourceBundle;

import javax.portlet.Event;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ProcessEvent;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

public class HelloPortlet extends GenericPortlet {
	private static final String EDIT_JSP_FILE = "/WEB-INF/jsp/editHello.jsp";
	private static final String HELP_MESSAGE = "label.message.help";

	@RenderMode(name = "VIEW")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PrintWriter pw = response.getWriter();
		String name = request.getParameter("name");
		name = (name == null) ? "" : name;
		String messagePattern = request.getPreferences().getValue("message",
				"Hello {0} !");
		pw.write(MessageFormat.format(messagePattern, name));
	}

	@RenderMode(name = "EDIT")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		String messagePattern = request.getPreferences().getValue("message",
				"Hello {0} !");
		request.setAttribute("message", messagePattern);
		getPortletContext().getRequestDispatcher(EDIT_JSP_FILE).include(
				request, response);
	}

	@ProcessAction(name = "messageAction")
	public void processActionEdit(javax.portlet.ActionRequest request,
			javax.portlet.ActionResponse respose) throws PortletException,
			IOException {
		PortletPreferences pref = request.getPreferences();
		String messagePattern = (String) request.getParameter("message");
		pref.setValue("message", messagePattern);
		pref.store();
		respose.setPortletMode(PortletMode.VIEW);
	}

	@RenderMode(name = "HELP")
	public void help(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		ResourceBundle bundle = getPortletConfig().getResourceBundle(
				request.getLocale());
		String help = bundle.getString(HELP_MESSAGE);
		PrintWriter pw = response.getWriter();
		pw.write(help);
	}

	@ProcessEvent(qname = "{http://test.portlet.org}name")
	@Override
	public void processEvent(EventRequest request, EventResponse response)
			throws PortletException, IOException {
		Event event = request.getEvent();
		String name = (String) event.getValue();
		response.setRenderParameter("name", name);
	}
}
